//
//  biomerLognViewController.m
//  dongfengTest
//
//  Created by wxt on 2021/3/18.
//

#import "BiomerLognViewController.h"
#import "LZActionSheetView.h"
#import "LognViewController.h"
#import "LoginPassWordViewController.h"
#import <LocalAuthentication/LocalAuthentication.h>
#import "HomeViewController.h"
#import "PassWordViewController.h"
#import "MoblieViewController.h"

#import "FaceIDViewController.h"
@interface BiomerLognViewController ()
@property (nonatomic, strong) UIView *headView;
@property (retain,nonatomic) LAContext *faceIDContext;
@property(nonatomic,strong)MBProgressHUD *hud;
@end
static SignMode mode = SignModeRaw;
static IMHashType hashType = IMHashTypeSM3;

@implementation BiomerLognViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = Wcolor;
    [self addUIView];
    // Do any additional setup after loading the view.
    
}

-(void)addUIView{
    //

    UIButton * backBtn =[UIButton createBtnFrame:CGRectMake(15, kStatusBarHeight+5, 18, 18) title:@"" bgImageName:@"fanhui" action:^(UIButton *button) {
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    [self.view addSubview:backBtn];
    
    UIButton * faceBtn = [UIButton createBtnFrame:CGRectMake(kWidth/2-60, 150, 120, 120) title:@"" bgImageName:@"" action:^(UIButton *button) {
        
        NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
        if ([[stand objectForKey:@"bio"] intValue] == 1) {
            NSString *localizedReason = [NSString stringWithFormat:@"%@识别",self.BiometryTypeStr];
            [self.faceIDContext evaluatePolicy:(LAPolicyDeviceOwnerAuthentication) localizedReason:localizedReason reply:^(BOOL success, NSError * _Nullable error) {
                if (success) {
                    //主线程
                    dispatch_async(dispatch_get_main_queue(), ^{
                        NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
                        [self loadLoginUrl];
                    });
                    
                }else{
                    NSLog(@"check error --->%@",error.localizedDescription);
                    
                    switch (error.code) {
                        case LAErrorSystemCancel:
                            NSLog(@"系统取消授权，例如其他APP切入");
                            break;
                        case LAErrorUserCancel:
                            NSLog(@"用户取消验证");
                            break;
                        case LAErrorAuthenticationFailed:
                            NSLog(@"授权失败");
                            break;
                        case LAErrorPasscodeNotSet:
                            NSLog(@"系统未设置密码");
                            break;
                        case LAErrorBiometryNotAvailable:
                            NSLog(@"设备生物ID不可用，例如未打开");
                            break;
                        case LAErrorBiometryNotEnrolled:
                            NSLog(@"设备生物ID不可用，用户未登录");
                            break;
                        case LAErrorUserFallback:{
                            
                            [[NSOperationQueue mainQueue]addOperationWithBlock:^{
                                NSLog(@"用户选择输入密码，切换到主线程");                 ;
                            }];
                            
                        }
                            
                            break;
                        default:{
                            
                            [[NSOperationQueue mainQueue]addOperationWithBlock:^{
                                NSLog(@"其他情况，切换到主线程");                 ;
                            }];
                            
                        }
                            break;
                    }
                    
                }
            }];
        }else{
      
    
            
            FaceIDViewController * faceVC =[[FaceIDViewController alloc]init];
            faceVC.modalPresentationStyle = 0;
            faceVC.pushPath = @"boi";
            faceVC.userName = self.userName;
            faceVC.BiometryTypeStr = self.BiometryTypeStr;
            faceVC.BiometryTypeNumber = self.BiometryTypeNumber;
            [self presentViewController:faceVC animated:YES completion:nil];
            

        }
        
       
        
        
        
        
    }];
    [self.view addSubview:faceBtn];
    
    if (self.BiometryTypeNumber == 1) {
        //指纹
        [faceBtn setBackgroundImage:[UIImage imageNamed:@"zhiwen"] forState:UIControlStateNormal];

 
      
    }else if(self.BiometryTypeNumber == 2){
        //面部
        [faceBtn setBackgroundImage:[UIImage imageNamed:@"renlianshibie"] forState:UIControlStateNormal];
    
   
    }
    TKLlable * faceLab = [TKLlable labelWithFrame:CGRectMake(kWidth/2-50, CGRectGetMaxY(faceBtn.frame)+10, 100, 20) text:[NSString stringWithFormat:@"%@识别登录",self.BiometryTypeStr] textColor:Bcolor font:Font_6(14) textAlignment:Textcenter backgroundColor:Ccolor];
    [self.view addSubview:faceLab];
    
    UIButton *moreBtn = [UIButton createBtnFrame:CGRectMake(kWidth/2-25, CGRectGetMaxY(faceLab.frame)+20, 50, 20) title:@"更多" bgImageName:@"" action:^(UIButton *button) {
        NSArray *array = @[@"密码登录"];
        LZActionSheetView *action = [[LZActionSheetView alloc] initWithTitleView:self.headView optionsArr: array cancelTitle:@"取消" cancelBlock:^{
            
        } selectBlock:^(NSInteger index) {
            
            if (index == 0) {
                //生物登录
                LoginPassWordViewController * faceVC = [[LoginPassWordViewController alloc]init];
                faceVC.userName = self.userName;
                faceVC.cerDN =  self.cerDn;
                faceVC.modalPresentationStyle = 0;
         
                
                [self presentViewController:faceVC animated:YES completion:nil];
            }
            
        }];
        [self.view addSubview:action];
    }];
    [moreBtn setTitleColor:JhColor(153, 153, 153) forState:UIControlStateNormal];
    [self.view addSubview:moreBtn];
    
}
-(void)loadLoginUrl{
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
      self.hud.labelText = NSLocalizedString(@"请稍等", @"HUD loading title");
   
    IMUser * user = [IMUser userWithUserName:self.userName];
    
    FMDatabase *database =  [DataBaseTool openDataBase];
    
    NSString *selectSql = [NSString stringWithFormat:@"select * from userCer where userName = '%@'",self.userName];

    FMResultSet *resultSet = [database executeQuery:selectSql];
    
    while ([resultSet next]) {

        NSString *payPassord  = [resultSet stringForColumn:@"payWord"];

        IMUser * user = [IMUser userWithUserName:self.userName];

        [user.cert signWithPIN:payPassord Plain:[NSString stringWithFormat:@"%@+%@",self.userName,[user.cert getCertInfoWithItem:CertItemTypeDN]] encoding:NSUTF8StringEncoding hashType:IMHashTypeSM3 mode:mode andCompleteBlock:^(int resultCode, NSString *signResult) {
            {
                if (resultCode == IM_ER_SUCCESS) {
//                    NSLog(@"%@",signResult);
                    if (signResult != nil) {
        
                        NSDictionary * dic =@{@"grantType":@"finger",@"password":[IMSecurity getDeviceIdentifier],@"username":self.userName,@"certDn":[user.cert getCertInfoWithItem:CertItemTypeDN],@"sign":signResult};
                        [self loginWithDic:dic];
                        
                    }
                }else{
                    self.hud.hidden = YES;
                    
                    [MBProgressHUD showError:@"签名失败" toView:self.view];
                }
            }
        }];
        
        
        
        
        
     
    }
    [database close];
    






    
}
-(void)loginWithDic:(NSDictionary *)dic{
    [AFNetworkUtils POST_Raw:kUser_Login_Api body:dic.yy_modelToJSONString head:nil success:^(NSDictionary * _Nonnull responseObject) {
            
        self.hud.hidden = YES;

        
        if ([responseObject[@"code"] intValue] ==200) {
            NSDictionary * dataDic= responseObject[@"data"];
             NSString * dataStr = dataDic[@"accessToken"];
            NSString *dealString =dataDic[@"tokenType"];
            NSString *resultString = [TKLTools strFirstBig:dealString];
            
            dataStr = [NSString stringWithFormat:@"%@ %@",resultString,dataStr];
             NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
             [stand setObject:dataStr forKey:@"token"];
             NSDictionary * dic = [TKLTools jwtDecodeWithJwtString:dataStr];
             NSString * jsonStr = dic[@"user_name"];
             NSDictionary * jsonDic = [TKLTools dictionaryWithJsonString:jsonStr];
             NSString * isChangePass = jsonDic[@"firstEnter"];
             
            [stand setObject:self.userName forKey:@"userName"];
//            [stand setObject:self.passWordFiled.text forKey:@"passWord"];

             //是否修改过密码  1和 2  均未修改

            //插入数据库
            [self insterDataList];
            
            
            
             if ([isChangePass intValue] == 1 || [isChangePass intValue] ==2) {
               
                 PassWordViewController * passVC = [[PassWordViewController alloc]init];
     
                 passVC.modalPresentationStyle = 0;
                 passVC.pushPath = @"newUser";
                 passVC.verifyCode = @"";
                 [self presentViewController:passVC animated:YES completion:nil];

             }else{
            
//进首页
                 HomeViewController * homeVC = [[HomeViewController alloc]init];
                 homeVC.modalPresentationStyle = 0;
                 
                 
                 [self presentViewController:homeVC animated:YES completion:nil];
                 
             }

        }else{
            
            
            [MBProgressHUD showError:responseObject[@"msg"] toView:self.view];

        }

        } failure:^(NSString * _Nonnull error) {
            self.hud.hidden = YES;
        }];
}

-(void)insterDataList{
    
    NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
    FMDatabase *database =  [DataBaseTool openDataBase];
    
    NSString *selectSql = [NSString stringWithFormat:@"select * from user where userName = '%@'",self.userName];

    FMResultSet *resultSet = [database executeQuery:selectSql];
   
    
    if ( [resultSet next]) {
        ;
    }else{
        NSString *insertSql = [NSString stringWithFormat:@"INSERT INTO 'user' ('userName', 'passWord') VALUES ('%@', '%@')",self.userName,[stand objectForKey:@"passWord"]];
               BOOL result = [database executeUpdate:insertSql];
      if (!result) {
          NSLog(@"插入失败");
      }else{
          NSLog(@"插入成功");
      }
        
    }
    
    [database close];
}

- (LAContext *)faceIDContext{
    if (!_faceIDContext) {
        _faceIDContext = [[LAContext alloc] init];
    }
    return _faceIDContext;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
